//
//  KFChoseGoodsView.m
//  KafeeSale
//
//  Created by Liboom on 2025/6/25.
//

#import "KFChoseGoodsView.h"
#import "KFChoseCell.h"
@interface KFChoseGoodsView()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic, strong) UIView *bgView;
@property(nonatomic, strong) UITableView *myTab;
@property(nonatomic, strong) UIView *botView,*countView;
@property(nonatomic, strong) UILabel *totalPriceLab,*totalCountLab;
@end
@implementation KFChoseGoodsView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.7];
        [self createUI];
    }
    return self;
}
-(void)createUI{
    UIButton * btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn2 addTarget:self action:@selector(closeView) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:btn2];
    btn2.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 580);
    
    self.bgView = [[UIView alloc]initWithFrame:Frame(0, SCREEN_HEIGHT - 580, SCREEN_WIDTH, 580)];
    self.bgView.backgroundColor = UIColor.whiteColor;
    self.bgView.cornerRadius = 10;
    [self addSubview:self.bgView];
    
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn addTarget:self action:@selector(closeView) forControlEvents:UIControlEventTouchUpInside];
    [btn setImage:[UIImage imageNamed:@"关闭"] forState:UIControlStateNormal];
    [self.bgView addSubview:btn];
    btn.sd_layout.rightSpaceToView(self.bgView, 10).topSpaceToView(self.bgView, 10).widthIs(35).heightEqualToWidth();
    
    UILabel * lab = [UILabel labelWithTitle:@"已购商品" color:UIColor.blackColor fontSize:16];
    [self.bgView addSubview:lab];
    lab.sd_layout.leftSpaceToView(self.bgView, 10).centerYEqualToView(btn).heightIs(16);
    [lab setSingleLineAutoResizeWithMaxWidth:300];
    
//    self.totalPriceLab = [UILabel labelWithTitle:@"" color:UIColor.blackColor fontSize:16];
//    [self.bgView addSubview:self.totalPriceLab];
//    self.totalPriceLab.sd_layout.leftSpaceToView(self.bgView, 10).centerYEqualToView(btn).heightIs(16);
//    [self.totalPriceLab setSingleLineAutoResizeWithMaxWidth:300];
    self.botView = [UIView new];
    self.botView.cornerRadius = 25;
    [self.botView addTarget:self action:@selector(closeView)];
    self.botView.backgroundColor = [UIColor colorWithRed:0.94 green:0.94 blue:0.94 alpha:1];
    [self.bgView addSubview:self.botView];
    self.botView.sd_layout.leftSpaceToView(self.bgView, 20).rightSpaceToView(self.bgView, 20).bottomSpaceToView(self.bgView, KTabbarSafeBottomMargin+30).heightIs(50);
    UIButton * cartBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cartBtn addTarget:self action:@selector(closeView) forControlEvents:UIControlEventTouchUpInside];
    [cartBtn setImage:[UIImage imageNamed:@"购物车"] forState:UIControlStateNormal];
    [self.botView addSubview:cartBtn];
    cartBtn.sd_layout.centerYEqualToView(self.botView).widthIs(45).heightEqualToWidth().leftSpaceToView(self.botView, 0);
    
    UIButton * orderBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    orderBtn.backgroundColor = [UIColor colorWithRed:0.85 green:0.87 blue:0.5 alpha:1];
    [orderBtn setTitle:@"下单" forState:UIControlStateNormal];
    [orderBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [orderBtn addTarget:self action:@selector(createOrder) forControlEvents:UIControlEventTouchUpInside];
    [self.botView addSubview:orderBtn];
    orderBtn.sd_layout.rightEqualToView(self.botView).topEqualToView(self.botView).bottomEqualToView(self.botView).widthIs(100);
    orderBtn.sd_cornerRadius = @0.5;
    
    self.totalPriceLab = [UILabel labelWithTitle:@"" color:RED_COLOR fontSize:25];
    [self.botView addSubview:self.totalPriceLab];
    self.totalPriceLab.sd_layout.leftSpaceToView(self.botView, 60).centerYEqualToView(self.botView).heightIs(20);
    [self.totalPriceLab setSingleLineAutoResizeWithMaxWidth:300];
    
    self.countView = [UIView new];
    self.countView.backgroundColor = RED_COLOR;
    self.countView.cornerRadius = 10;
    self.countView.hidden = YES;
    [self.bgView addSubview:self.countView];
    self.countView.sd_layout.centerXIs(60).bottomSpaceToView(self.bgView, KTabbarSafeBottomMargin+60).heightIs(20);
    
    self.totalCountLab = [UILabel labelWithTitle:@"1" color:UIColor.whiteColor fontSize:13];
    [self.countView addSubview:self.totalCountLab];
    self.totalCountLab.sd_layout.leftSpaceToView(self.countView, 7).topEqualToView(self.countView).bottomEqualToView(self.countView);
    [self.totalCountLab setSingleLineAutoResizeWithMaxWidth:300];
    [self.countView setupAutoWidthWithRightView:self.totalCountLab rightMargin:7];
    
    [self.bgView addSubview:self.myTab];
}
-(void)createOrder{
    self.orderDownBlock();
}
- (void)calTotalPrice {
    CGFloat price = 0;
    NSInteger count = 0;
    for (int i = 0; i < self.dataArr.count; i++) {
        KFProductModel *product = self.dataArr[i];
        if (product.choseCount) {
            // 计算当前商品总价：基础价格 + 规格价格 + 做法价格
            CGFloat basePrice = product.price;
            
            // 加上规格价格（如果有选中的规格）
            if (product.selectedSpecs && product.selectedSpecs.count > 0) {
                KFDishSpecList *spec = product.selectedSpecs.firstObject;
                basePrice += spec.specPrice;
            }
            
            // 加上做法价格（多选）
            if (product.selectedPractices && product.selectedPractices.count > 0) {
                for (NSDictionary *practice in product.selectedPractices) {
                    CGFloat practicePrice = [practice[@"cookPrice"] floatValue];
                    basePrice += practicePrice;
                }
            }
            
            price += basePrice * product.choseCount;
            count += product.choseCount;
        }
    }
    self.totalPriceLab.text = [NSString stringWithFormat:@"￥%.0lf", price];
    if (count > 0) {
        self.countView.hidden = NO;
        self.totalCountLab.text = [NSString stringWithFormat:@"%ld", count];
    } else {
        self.countView.hidden = YES;
    }
}
- (void)setDataArr:(NSMutableArray *)dataArr{
    _dataArr = dataArr;
    [self.myTab reloadData];
    [self calTotalPrice];
}
-(void)closeView{
    [UIView animateWithDuration:0.3 animations:^{
        self.bgView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 580);
        self.alpha = 0;
    } completion:^(BOOL finished) {
        if (self.closeBlock) {
            self.closeBlock();
        }
        [self removeFromSuperview];
    }];
}
#pragma mark 代理方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    KFChoseCell * cell = [tableView dequeueReusableCellWithIdentifier:@"KFChoseCell"];
    KFProductModel * mo = self.dataArr[indexPath.row];
    cell.model = mo;
    MJWeakSelf
    cell.reloadBlock = ^{
        [weakSelf calTotalPrice];
    };
    
    // 添加移除商品的回调
    cell.removeGoodsBlock = ^(KFProductModel *model) {
        // 从数据源中移除商品
        [weakSelf.dataArr removeObject:model];
        // 刷新表格
        [weakSelf.myTab reloadData];
        // 重新计算总价
        [weakSelf calTotalPrice];
        
        // 如果所有商品都被移除了，关闭视图
        if (weakSelf.dataArr.count == 0) {
            [weakSelf closeView];
        }
    };
    
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    KFProductModel *mo = self.dataArr[indexPath.row];
    
    // 使用SDAutoLayout计算自适应高度
    return [tableView cellHeightForIndexPath:indexPath
                                    model:mo
                                  keyPath:@"model"
                                cellClass:[KFChoseCell class]
                         contentViewWidth:SCREEN_WIDTH];
}

// 或者你也可以使用estimatedHeightForRowAtIndexPath来优化性能
-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 107; // 提供一个预估高度
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 20;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    KFProductModel *mo = self.dataArr[indexPath.row];
        
        // 先关闭当前视图
        [self closeView];
        
        // 延迟一下，确保动画完成后再弹出规格选择
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (self.selectGoodsBlock) {
                self.selectGoodsBlock(mo);
            }
        });
}
- (UITableView *)myTab {
    if (!_myTab) {
        _myTab = [[UITableView alloc] initWithFrame:Frame(0, 55, SCREEN_WIDTH, 400) style:UITableViewStyleGrouped];
        _myTab.dataSource = self;
        _myTab.delegate = self;
        _myTab.backgroundColor = UnderLineColor;
        _myTab.rowHeight = 90;
        [_myTab registerClass:[KFChoseCell class] forCellReuseIdentifier:@"KFChoseCell"];

    }
    return _myTab;
}

@end
